import React, { useState, useEffect, useCallback, useRef } from 'react';
import { Table, Button, Input, Select, Form, Modal, Typography, Space, Spin, Empty, App } from 'antd';
import { EditOutlined, DeleteOutlined, MenuOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { removeEmptyParams } from '../utils/removeEmptyParams';
import type { PromptTemplate } from '../types/template';
import { DndContext } from '@dnd-kit/core';
import { restrictToVerticalAxis } from '@dnd-kit/modifiers';
import { SortableContext, verticalListSortingStrategy } from '@dnd-kit/sortable';
import { useSortable } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { get, post } from '../utils/request';

const { Title } = Typography;

const typeOptions = [
  { label: '简单选择', value: 'text' },
  { label: '问卷模版', value: 'question' },
  { label: '框架+问卷', value: 'framework' },
];

// 可排序的行组件
const SortableRow = ({ children, ...props }: any) => {
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
    isDragging,
  } = useSortable({
    id: props['data-row-key'],
  });

  const style: React.CSSProperties = {
    ...props.style,
    transform: CSS.Transform.toString(transform),
    transition,
    cursor: 'move',
    ...(isDragging ? { position: 'relative', zIndex: 9999 } : {}),
  };

  return (
    <tr {...props} ref={setNodeRef} style={style} {...attributes}>
      {React.Children.map(children, (child) => {
        if (child.key === 'sort') {
          return React.cloneElement(child, {
            children: (
              <MenuOutlined
                className="drag-handle"
                style={{ cursor: 'move', color: '#999' }}
                {...listeners}
              />
            ),
          });
        }
        return child;
      })}
    </tr>
  );
};


const PromptTemplateManager: React.FC = () => {
  const { message } = App.useApp();
  const [form] = Form.useForm();
  const [data, setData] = useState<PromptTemplate[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [sceneOptions, setSceneOptions] = useState<{label: string, value: number}[]>([]);
  const [sceneLoading, setSceneLoading] = useState(false);
  const [sceneMap, setSceneMap] = useState<Record<number, string>>({});
  const [deleteModalVisible, setDeleteModalVisible] = useState(false);
  const [deleteId, setDeleteId] = useState<number | null>(null);
  const navigate = useNavigate();
  const tableBodyRef = useRef<HTMLDivElement>(null);

  // 拉取场景下拉
  useEffect(() => {
    setSceneLoading(true);
    get('/api/admin/template/scene/list')
      .then((res: any) => {
        if (res && Array.isArray(res.list)) {
          setSceneOptions(res.list.map((item: any) => ({ label: item.sceneName, value: item.id })));
          setSceneMap(res.list.reduce((acc: any, cur: any) => { acc[cur.id] = cur.sceneName; return acc; }, {}));
        } else {
          setSceneOptions([]);
          setSceneMap({});
        }
      })
      .catch(() => {
        setSceneOptions([]);
        setSceneMap({});
      })
      .finally(() => setSceneLoading(false));
  }, []);

  // 查询
  const fetchData = useCallback(async (params: any = {}) => {
    setLoading(true);
    setError('');
    try {
      const queryObj = removeEmptyParams({
        nameLike: params.nameLike,
        type: params.type,
        sceneId: params.sceneId,
      });
      const result = await get('/api/admin/template/list', queryObj);
      setData(result.list || []);
    } catch (error) {
      setData([]);
      setError('网络异常，请稍后重试');
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchData({});
  }, [fetchData]);

  // 查询
  const handleSearch = () => {
    fetchData({
      ...form.getFieldsValue(),
    });
  };

  // 重置
  const handleReset = () => {
    form.resetFields();
    fetchData({});
  };

  // 发布操作
  const handlePublish = async (id: number) => {
    try {
      await post('/api/admin/template/publish', { id });
      message.success('发布成功！');
      fetchData({
        ...form.getFieldsValue(),
      });
    } catch (error) {
      // 错误已在request中处理
    }
  };

  // 删除操作
  const handleDelete = useCallback(async () => {
    if (!deleteId) return;
    try {
      await post('/api/admin/template/delete', { id: deleteId });
      message.success('删除成功');
      setDeleteModalVisible(false);
      setDeleteId(null);
      fetchData({
        ...form.getFieldsValue(),
      });
    } catch (error) {
      // 错误已在request中处理
    }
  }, [deleteId, fetchData, form]);

  // 处理拖拽开始
  const handleDragStart = () => {
    const tableBody = tableBodyRef.current?.querySelector('.ant-table-body');
    if (tableBody) {
      (tableBody as HTMLElement).style.overflow = 'hidden';
    }
  };

  // 处理拖拽结束
  const handleDragEnd = () => {
    const tableBody = tableBodyRef.current?.querySelector('.ant-table-body');
    if (tableBody) {
      (tableBody as HTMLElement).style.overflow = 'auto';
    }
  };

  // 处理拖拽结束
  const onDragEnd = async ({ active, over }: any) => {
    if (active.id !== over?.id) {
      const oldIndex = data.findIndex((item) => item.id === active.id);
      const newIndex = data.findIndex((item) => item.id === over?.id);
      
      // 更新本地数据
      const newData = [...data];
      const [removed] = newData.splice(oldIndex, 1);
      newData.splice(newIndex, 0, removed);
      setData(newData);

      // 调用排序接口
      try {
        await post('/api/admin/template/sort/set', {
          ids: newData.map(item => item.id)
        });
      } catch (error) {
        // 如果失败，重新获取数据
        fetchData({
          ...form.getFieldsValue(),
        });
      }
    }
  };

  const columns = [
    {
      title: '排序',
      dataIndex: 'sort',
      width: 60,
      className: 'drag-visible',
      key: 'sort',
    },
    { title: '模版名称', dataIndex: 'name', key: 'name', width: '22%' },
    { title: '模版形式', dataIndex: 'type', key: 'type', width: '15%', render: (v: string) => {
      const t = typeOptions.find(opt => opt.value === v); return t ? t.label : v;
    } },
    { title: '关联场景', dataIndex: 'sceneId', key: 'sceneId', width: '18%', render: (v: number) => sceneMap[v] || v },
    { title: '模版描述', dataIndex: 'templateDesc', key: 'templateDesc', width: '25%' },
    { title: '操作', key: 'action', width: '20%', render: (_: any, record: any) => (
      <Space size="small">
        <Button type="link" size="small" icon={<EditOutlined />} onClick={() => navigate(`/template-edit/${record.id}`)}>
          编辑
        </Button>
        <Button 
          type="link" 
          size="small"
          danger 
          icon={<DeleteOutlined />}
          onClick={() => {
            setDeleteId(record.id);
            setDeleteModalVisible(true);
          }}
        >
          删除
        </Button>
      </Space>
    ) },
  ];

  return (
    <div style={{ 
      background: '#fff', 
      padding: '0px 8px',
      height: '100vh',
      display: 'flex',
      flexDirection: 'column',
      overflow: 'hidden'
    }}>
      <Title level={5} style={{ textAlign: 'left', margin: '12px 0', fontWeight: 600, fontSize: 18 }}>提示词模版管理</Title>
      <Spin spinning={loading} tip="加载中...">
        {error && <div style={{ color: 'red', marginBottom: 16 }}>{error}</div>}
        <Form form={form} layout="inline" style={{ marginBottom: 16 }}>
          <Form.Item name="nameLike" label="模版名称">
            <Input placeholder="请输入模版名称" style={{ width: 200 }} />
          </Form.Item>
          <Form.Item name="type" label="模版形式">
            <Select
              placeholder="请选择模版形式"
              style={{ width: 200 }}
              options={typeOptions}
              allowClear
            />
          </Form.Item>
          <Form.Item name="sceneId" label="关联场景">
            <Select
              placeholder="请选择关联场景"
              style={{ width: 200 }}
              options={sceneOptions}
              loading={sceneLoading}
              allowClear
            />
          </Form.Item>
          <Form.Item>
            <Button type="primary" onClick={handleSearch} loading={loading}>查询</Button>
            <Button style={{ marginLeft: 8 }} onClick={handleReset} disabled={loading}>重置</Button>
          </Form.Item>
        </Form>
        <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 16 }}>
          <Button type="primary" onClick={() => navigate('/template-edit')}>新增</Button>
        </div>
        <div style={{ flex: 1, overflow: 'auto', minHeight: 0 }} ref={tableBodyRef}>
          <DndContext 
            modifiers={[restrictToVerticalAxis]} 
            onDragEnd={(event) => {
              handleDragEnd();
              onDragEnd(event);
            }}
            onDragStart={handleDragStart}
          >
            <SortableContext
              items={data.map((i) => i.id)}
              strategy={verticalListSortingStrategy}
            >
              <Table
                components={{
                  body: {
                    row: SortableRow,
                  },
                }}
                pagination={false}
                columns={columns}
                dataSource={data}
                rowKey="id"
                scroll={{ y: 'calc(100vh - 280px)' }}
                bordered
                locale={{ emptyText: error ? <Empty description={error} /> : <Empty description="暂无数据" /> }}
                style={{ width: '100%' }}
                size="middle"
              />
            </SortableContext>
          </DndContext>
        </div>
      </Spin>
      <Modal
        title="删除确认"
        open={deleteModalVisible}
        onOk={handleDelete}
        onCancel={() => {
          setDeleteModalVisible(false);
          setDeleteId(null);
        }}
        okText="确认"
        cancelText="取消"
        okButtonProps={{ danger: true }}
      >
        <p>确定要删除这个模版吗？删除后无法恢复。</p>
      </Modal>
    </div>
  );
};

export default PromptTemplateManager;

// 添加全局样式
const style = document.createElement('style');
style.textContent = `
  .ant-table-body {
    overscroll-behavior: none !important;
  }
  .ant-table-body::-webkit-scrollbar {
    width: 6px;
    height: 6px;
  }
  .ant-table-body::-webkit-scrollbar-thumb {
    background: #ccc;
    border-radius: 3px;
  }
  .ant-table-body::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
  }
  .ant-table-row {
    cursor: grab;
  }
  .ant-table-row:active {
    cursor: grabbing;
  }
`;
document.head.appendChild(style); 